import Clipboard from 'clipboard';
import headerImgUploader from "../Components/headerImgUploader";
import validate from '../../libs/validate';
const liveProgramEditBtn = (h, param, vm) => {
    return h('Button', {
        style: {
            'margin-right': '10px',
        },
        props: {
            type: "primary",
            icon: 'edit',
            shape: "circle"

        },
        on: {
            click: () => {
                vm.selectData = param.row;
                vm.uploadImgCallbackPath = vm.selectData.cover_url;
                vm.$nextTick(()=>{
                    vm.liveProgramForm = {
                        name: vm.selectData.name,
                        live_address: vm.selectData.live_address,
                        start_time: new Date(vm.selectData.start_time.replace(/-/g, '/')),
                        end_time: new Date(vm.selectData.end_time.replace(/-/g, '/')),
                        intro: vm.selectData.intro,
                        detail: vm.selectData.detail,
                        status: vm.selectData.status,
                        live_room_uuid: vm.selectData.live_room_uuid,
                        vod_video_file_info_uuid:vm.selectData.vod_video_file_info_uuid
                    }

                })

                vm.showModal = true;
            }
        }
    })
};
const liveProgramDeleteBtn = (h, param, vm) => {
    return h(
        "Poptip", {
            props: {
                confirm: true,
                title: "您确定要删除此节目?",
                transfer: true
            },
            style: {
                'margin-right': '10px',
            },
            on: {
                "on-ok": () => {
                    // this.ignoreFeedback(param.row)

                    vm.deleteProgram(param.row)
                }
            }
        }, [
            h('Button', {
                style: {},
                props: {
                    type: "error",
                    icon: 'trash-b',
                    shape: "circle"
                },
                on: {
                    click: () => {

                    }
                }
            })
        ]
    )

}
const getLiveStreamBtn = (h, param, vm) => {
    let disabled = false;
    if (param.row.status !== '1') {
        disabled = true;

    }
    return h('Button', {
        props: {
            type: "success",
            icon: 'code-working',
            shape: "circle",
            disabled: disabled,
            loading: param.row.loading
        },
        on: {
            click: () => {

                vm.getLiveStream(param)
            }
        }
    })
}
export default {
    components: {
        headerImgUploader
    },
    computed: {
        user() {
            return this.$store.state.user.data
        }
    },
    data() {

        return {
            liveProgramTableColumns: [{
                'title': '图片',
                'align': 'center',
                'key': 'cover_url',
                'isImg': true,
                'width': 80
            }, {
                'title': '节目名称',
                'align': 'center',
                'key': 'name',
                'width': 250


            }, {
                'title': '当前状态',
                'align': 'center',
                'key': 'status',
                'width': 130

            }, {
                'title': '开始时间',
                'align': 'center',
                'key': 'start_time',
                'width': 200


            }, {
                'title': '结束时间',
                'align': 'center',
                'key': 'end_time',
                'width': 200

            }, {
                'title': '直播地址',
                'align': 'center',
                'key': 'live_address',
                'width': 200


            }, {
                'title': '操作',
                'align': 'center',
                'key': 'action',
                'action': true,
                'width': 160,
                'fixed': 'right'

            }],
            searchKey: '',
            pageCount: 0,
            pageNum: 1,
            pageLoading: false,
            liveProgramList: [],
            selectData: '',
            selectRoom: {
                uuid: ''
            },
            showModal: false,
            uploadImgCallbackPath: '',
            liveProgramForm: {
                name: '',
                live_address: '',
                start_time: new Date(),
                end_time: new Date(),
                intro: '',
                detail: '',
                status: '0',
                vod_video_file_info_uuid:''
            },
            liveProgramFormRules: {
                name: [{
                    required: true,
                    validator: validate.name,
                    trigger: 'blur'
                }],
                live_address: [{
                    required: true,
                    validator: validate.name,
                    trigger: 'blur'
                }],
                start_time: [{
                    required: true,
                    type: 'date',
                    message: '请选择日期',
                    trigger: 'change'
                }],
                end_time: [{
                    required: true,
                    type: 'date',
                    message: '请选择日期',
                    trigger: 'change'
                }],
                status: [{
                    required: true,
                    message: '请选择节目的状态',
                    trigger: 'change'
                }],
                vod_video_file_info_uuid:[{
                    required: true,
                    message: '请选择视频',
                    trigger: 'change'
                }],
            },
            uploadImgData: {},
            imgUploadUrl: '',
            modalLoading: true,
            liveRoomList: [{
                title: '全部',
                expand: true,
                children: [],
                uuid: '',
                selected: true
            }],
            clipboard: '',
            videoListLoading:false,
            videoList:[]
        }
    },
    methods: {
        /**
         * @param {Boolean} type
         * 设置确定按钮loading动画，传True或者False
         */
        changeLoadingStatus(type) {
            if (!type) {
                this.modalLoading = false;
            }
            this.$nextTick(() => {
                this.modalLoading = true;
            });
        },
        doSearch() {
            this.pageNum = 1;
            this.getLiveProgramList();
        },
        clearSearch() {
            this.searchKey = '';
            this.pageNum = 1;
            this.getLiveProgramList();
        },
        changePage(num) {
            this.pageNum = num;
            this.getLiveProgramList();
            document.querySelector('.single-page-con').scrollTo(0, 0)

        },
        doGetLiveRoomList() {
            this.http.post(this.postUrl.doGetLiveRoomListUrl, {
                token: this.user.tokenList[0],
                all: '1'
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {
                    data.data.forEach(item => {
                        item.title = item.type_name
                    })
                    this.$set(this.liveRoomList[0], 'children', JSON.parse(JSON.stringify(data.data)))
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                // this.errorHandle()
            })
        },

        getLiveProgramList(roomUuid) {
            if (this.pageLoading) return
            this.pageLoading = true;
            this.http.post(this.postUrl.doGetLiveProgramListUrl, {
                token: this.user.tokenList[0],
                pageNum: this.pageNum,
                pageSize: 10,
                live_room_uuid: '' || roomUuid,
                key_word: this.searchKey
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {
                    this.pageCount = data.data.totalRow;
                    this.liveProgramList = JSON.parse(JSON.stringify(data.data.list));

                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle()
            }).then(() => {
                this.pageLoading = false;
            })
        },
        uploadImgSuccess(data) {
            this.uploadImgCallbackPath = data;
        },
        createImgUploadData() {
            //上传图片
            let uploadImgData = {
                token: this.user.tokenList[0],
                type: 1,
                app_key: this.http.app_key,
                timestamp: "2017-09-26 15:52:28"
            }
            let uploadImgDataSign = this.http.getSign({
                type: 1,
                token: this.user.tokenList[0]
            });
            uploadImgData.sign = uploadImgDataSign;
            this.uploadImgData = uploadImgData;
        },
        openAddModal() {
            if (!this.selectRoom.uuid) {
                this.$Notice.warning({
                    title: '注意',
                    desc: "请先选择一个直播间！"
                })
                return;
            }
            this.showModal = true;
        },
        clickOK() {
            this.changeLoadingStatus(true)
            if (!this.uploadImgCallbackPath) {
                this.changeLoadingStatus(false);
                this.errorHandle("请先上传图片！");
                return;
            }

            this.$refs.liveProgramForm.validate(valid => {
                if (!valid) {
                    this.changeLoadingStatus(false);
                    return
                }
                let postData = JSON.parse(JSON.stringify(this.liveProgramForm));
                postData.cover_url = this.uploadImgCallbackPath;
                postData.token = this.user.tokenList[0];

                if (this.selectData) {
                    postData.uuid = this.selectData.uuid;
                } else {
                    postData.live_room_uuid = this.selectRoom.uuid

                }
                postData.start_time = this.liveProgramForm.start_time.getTime();
                postData.end_time = this.liveProgramForm.end_time.getTime();
                this.http.post(this.postUrl.doAddOrEditLiveProgram, postData).then((data) => {
                    if (data.code > -1) {
                        this.$Notice.success({
                            title: this.selectData ? '修改成功！' : '新增成功！'
                        })
                        this.showModal = false;
                        this.getLiveProgramList(this.selectRoom.uuid);
                    } else {
                        this.errorHandle(data.msg)
                    }
                    this.changeLoadingStatus(false)

                }, () => {
                    this.errorHandle()
                    this.changeLoadingStatus(false)

                })
            })
        },
        deleteProgram(param) {
            this.http.post(this.postUrl.doDeleteProgramUrl, {
                token: this.user.tokenList[0],
                uuid: param.uuid
            }).then((data) => {
                if (data.code > -1) {
                    this.$Notice.success({
                        title: '操作成功！',
                    })
                    this.getLiveProgramList(this.selectRoom.uuid);
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle()
            })
        },
        goLiveRoom() {
            this.$router.push({
                name: 'live-ctrl-room'
            })
        },
        onSelectChange(e) {
            console.log(e);
            this.selectRoom = e[0];
            document.querySelector('.single-page-con').scrollTo(0, 0)
            this.pageNum = 1;
            this.getLiveProgramList(e[0].uuid)
        },
        getLiveStream(param) {
            this.$set(this.liveProgramList[param.index], 'loading', true)
            this.http.post(this.postUrl.doCreatLiveStreamUrl, {
                token: this.user.tokenList[0],
                uuid: param.row.uuid,
                status: param.row.status
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {

                    // console.log(this.clipboard);
                    this.$Modal.confirm({
                        title:'推流地址',
                        render: (h) => {
                            return h('Input', {
                                style:{
                                    'margin-top':'20px'
                                },
                                props: {
                                    value: data.data,
                                },
                            },[
                                h('Button',{
                                    style:{
                                        'height':'32px'
                                    },
                                    slot:'append',
                                    attrs:{
                                            'id':'streamBtn'  + param.index,
                                            'data-stream-url':data.data
                                    }
                                },[
                                    h('Icon',{
                                        props:{
                                            type:'clipboard',
                                            size:18
                                        }
                                    })
                                ])
                            ])
                        },
                        onOk:()=>{
                            this.clipboard.destroy()

                        },
                        onCancel:()=>{
                            this.clipboard.destroy()

                        }
                    })
                    this.clipboard = new Clipboard('#'+'streamBtn'  + param.index,{
                        text:(trigger)=>{
                            this.$Message.success('推流地址已复制到剪贴板')
                            return trigger.getAttribute('data-stream-url')
                        }
                    })
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle('获取推流地址失败，请检查网络')

            }).then(() => {
                this.$set(this.liveProgramList[param.index], 'loading', false)
            })
        },
        getVideoList() {
            if (this.videoListLoading) return
            this.videoListLoading = true;
            this.http.post(this.postUrl.doGetVideoList, {
                token: this.user.tokenList[0],
                all:'1'
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {
                    this.videoList = JSON.parse(JSON.stringify(data.data));
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                // this.errorHandle()
            }).then(() => {
                this.videoListLoading = false;
            })
        },

    },
    created() {
        this.liveProgramTableColumns.forEach(item => {
            if (item.isImg) {
                item.render = (h, param) => {
                    return h("img", {
                        attrs: {
                            src: this.postUrl.imgPath + param.row.cover_url
                        },
                        style: {
                            width: "100%",
                            height: "auto",
                            "margin-top": "5px"
                        }
                    });
                };
            }
            if (item.key === 'status') {
                item.render = ((h, param) => {
                    let statusText = '未开始'
                    switch (param.row.status) {
                        case '0':
                            statusText = '未开始'
                            break;
                        case '1':
                            statusText = '进行中'
                            break;
                        case '2':
                            statusText = '已结束'
                            break;
                    }
                    return h('span', statusText)
                })
            }
            if (item.action) {
                item.render = ((h, param) => {
                    return h('div', [
                        liveProgramEditBtn(h, param, this),
                        liveProgramDeleteBtn(h, param, this),
                        getLiveStreamBtn(h, param, this)
                    ])
                })

            }
        })
        if (this.user) {
            this.getLiveProgramList()
            this.doGetLiveRoomList()
            this.createImgUploadData()
        }

    },
    watch: {
        user(val, old) {
            if (!old && val) {
                this.getLiveProgramList()
                this.doGetLiveRoomList()
                this.createImgUploadData()

            }
        },
        showModal(val) {
            if (!val) {
                this.selectData = '';
                this.uploadImgCallbackPath = "";
                this.liveProgramForm = {
                    name: '',
                    live_address: '',
                    start_time: new Date(),
                    end_time: new Date(),
                    intro: '',
                    detail: '',
                    status: '0',
                    vod_video_file_info_uuid:''
                }
                this.$refs.liveProgramForm.resetFields()

            }else{
                if(this.videoList.length == 0){
                    this.getVideoList()
                }
            }
        }
    }
}
